package org.oschina.api.user.active.queue;

import java.util.List;

import org.oschina.Constants;
import org.oschina.api.user.active.dao.UserActiveDAO;
import org.oschina.api.user.active.model.UserActivePushBean;
import org.oschina.api.user.follow.dao.UserFollowDAO;
import org.oschina.queue.BaseQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 用户动态推送队列
 */
@Component
public class UserActivePushQueue extends BaseQueue {

	@Autowired
	private UserFollowDAO userFollowDAO;
	@Autowired
	private UserActiveDAO userActiveDAO;
	
	private final int BATCH_COUNT=10;
	
	@Scheduled(fixedDelay=1000)
	public synchronized void handle()
	{
		UserActivePushBean bean=(UserActivePushBean) get(Constants.QUEUE_USER_ACTIVE_PUSH, UserActivePushBean.class);
		if(bean==null)
			return;
		
		int count=userFollowDAO._getOnlineByTarget(bean.getAuthor());
		if(count==0)
			return;
		
		int len=count/BATCH_COUNT;
		if(count%BATCH_COUNT!=0)
			len++;
		
		for(int i=0;i<len;i++)
		{
			List<Integer> ids=userFollowDAO._findOnlineIdByTarget(bean.getAuthor(), BATCH_COUNT*i, BATCH_COUNT);
			for(Integer id:ids)
			{
				userActiveDAO._pushByAuthorAndFollow(id, bean.getActive());
				userActiveDAO._updateCountByAuthorAndFollow(id, 1);
			}
		}
	}
}